<template>
  <div class="commodity-list">
    <!-- 顶部操作栏 -->
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.cmdtyTitle" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品简介">
          <el-input v-model="searchForm.cmdtyBrief" placeholder="请输入商品简介"></el-input>
        </el-form-item>
        <el-form-item label="商品标签">
          <el-input v-model="searchForm.cmdtyTag" placeholder="请输入商品标签"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>


    <div class="header-actions">
      <el-button type="primary" @click="cartVisible = true" class="cart-button">
        <el-icon><ShoppingCart /></el-icon>
        购物车
        <el-badge v-if="cartItems.length > 0" :value="cartItems.length" class="cart-badge" />
      </el-button>
    </div>

    <!-- 商品列表区域 -->
    <div class="commodity-grid">
      <el-row :gutter="20">
        <el-col :span="6" v-for="item in commodityList" :key="item.cmdtyId">
          <el-card class="commodity-card">
            <div class="commodity-info">
              <h3 class="commodity-title">{{ item.cmdtyTitle }}</h3>
              <p>{{ item.cmdtyBrief }}</p>
              <div class="price">¥{{ item.cmdtyCost }}</div>
              <div class="tag" v-if="item.cmdtyTag">{{ item.cmdtyTag }}</div>
              <div class="info-item time">
                上架时间：{{ item.cmdtyAddedAt }}
              </div>
              <div class="quantity-control">
                <el-button size="small" @click="decreaseItemQuantity(item)">-</el-button>
                <span class="quantity">{{ getItemSelectedQuantity(item.cmdtyId) }}</span>
                <el-button size="small" @click="increaseItemQuantity(item)">+</el-button>
              </div>
              <el-button 
                type="primary" 
                size="small" 
                class="add-to-cart-btn" 
                @click="addToCart(item)"
              >
                加入购物车
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 购物车弹窗 -->
    <el-dialog
      v-model="cartVisible"
      title="购物车"
      width="50%"
    >
      <div class="cart-content">
        <div v-for="item in cartItems" :key="item.cmdtyId" class="cart-item">
          <div class="cart-item-info">
            <h4>{{ item.cmdtyTitle }}</h4>
            <p>{{ item.cmdtyBrief }}</p>
            <p class="price">¥{{ item.cmdtyCost }}</p>
          </div>
          <div class="cart-item-quantity">
            <el-button @click="decreaseCartItemQuantity(item)">-</el-button>
            <span class="quantity">{{ item.quantity }}</span>
            <el-button @click="increaseCartItemQuantity(item)">+</el-button>
          </div>
          <el-button type="danger" @click="removeFromCart(item)">删除</el-button>
        </div>
        <div class="cart-total">
          <span>总计：</span>
          <span class="total-price">¥{{ cartTotal.toFixed(2) }}</span>
        </div>
        <el-button type="success" style="width: 100%; margin-top: 16px;" @click="handlePurchase">购买</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import type { Commodity } from '@/types/commodity'
import { ShoppingCart } from '@element-plus/icons-vue'
import { getCommodityApi } from '@/api/commodity'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/islogin'
import { addOrderApi } from '@/api/order'

// 定义购物车项类型
interface CartItem extends Commodity {
  quantity: number
}
//获取用户登录数据
const useUser=useUserStore()

// 商品列表数据
const commodityList = ref<Commodity[]>([])

// 搜索表单数据
const searchForm = ref<Commodity>({
  cmdtyId: 0,
  cmdtyTitle: '',
  cmdtyBrief: '',
  cmdtyCost: 0,
  cmdtyMgrId: "",
  cmdtyAddedAt: ''
})

// 购物车数据
const cartItems = ref<CartItem[]>([])

// 商品选择数量记录
const selectedQuantities = ref<Map<number, number>>(new Map())

// 弹窗控制
const cartVisible = ref(false)

// 计算购物车总价
const cartTotal = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + (item.cmdtyCost * item.quantity)
  }, 0)
})

// 获取商品的选择数量
const getItemSelectedQuantity = (cmdtyId: number) => {
  return selectedQuantities.value.get(cmdtyId) || 0
}

// 增加商品选择数量
const increaseItemQuantity = (commodity: Commodity) => {
  const currentQuantity = getItemSelectedQuantity(commodity.cmdtyId)
  selectedQuantities.value.set(commodity.cmdtyId, currentQuantity + 1)
}

// 减少商品选择数量
const decreaseItemQuantity = (commodity: Commodity) => {
  const currentQuantity = getItemSelectedQuantity(commodity.cmdtyId)
  if (currentQuantity > 0) {
    selectedQuantities.value.set(commodity.cmdtyId, currentQuantity - 1)
  }
}

// 增加购物车商品数量
const increaseCartItemQuantity = (item: CartItem) => {
  item.quantity++
}

// 减少购物车商品数量
const decreaseCartItemQuantity = (item: CartItem) => {
  if (item.quantity > 1) {
    item.quantity--
  }
}

// 添加到购物车
const addToCart = (commodity: Commodity) => {
  const quantity = getItemSelectedQuantity(commodity.cmdtyId)
  if (quantity <= 0) return

  const existingItem = cartItems.value.find(item => item.cmdtyId === commodity.cmdtyId)
  if (existingItem) {
    existingItem.quantity += quantity
  } else {
    cartItems.value.push({
      ...commodity,
      quantity: quantity
    })
  }
  
  // 重置选择数量
  selectedQuantities.value.set(commodity.cmdtyId, 0)
}

// 从购物车移除
const removeFromCart = (item: CartItem) => {
  const index = cartItems.value.findIndex(cartItem => cartItem.cmdtyId === item.cmdtyId)
  if (index !== -1) {
    cartItems.value.splice(index, 1)
  }
}

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑将由用户实现
  getcommodityList()
}

// 购买处理
const handlePurchase = async () => {
  if(!useUser.user){
    ElMessage.error("请登录后重试")
    return
  }
  for(const item of cartItems.value){
    const orderData={
      ordfCmdtyId:item.cmdtyId,
      ordfUserId:useUser.user.userId,
      ordfCount:item.quantity,
      ordfTotalAmt: Number((item.cmdtyCost * item.quantity).toFixed(3)),
      ordfState:"PENDING_SHIP"
    }
    const res = await addOrderApi(orderData)
    if(res.code==200){
      ElMessage.success(res.msg)
      cartVisible.value=false
      cartItems.value=[]
    }else{
      ElMessage.error(res.msg)
    }
  }
}

const getcommodityList =async ()=>{
  const res = await getCommodityApi(searchForm.value)
  if(res.code==200){
    commodityList.value = res.data
    ElMessage.success(res.msg)
  }else{
    ElMessage.error(res.msg)
  }
}

// 页面加载时获取商品数据
onMounted(() => {
  getcommodityList()
})
</script>

<style scoped>
.commodity-list {
  padding: 20px;
}

.header-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.cart-button {
  position: relative;
}

.cart-badge {
  position: absolute;
  top: -8px;
  right: -8px;
}

.search-area {
  margin-bottom: 20px;
}

.commodity-grid {
  margin-top: 20px;
}

.commodity-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.commodity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.commodity-info {
  padding: 15px;
}

.commodity-title {
  cursor: pointer;
  color: #409eff;
  margin: 0 0 10px 0;
}

.commodity-title:hover {
  text-decoration: underline;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
}

.tag {
  display: inline-block;
  padding: 2px 8px;
  background-color: #ecf5ff;
  color: #409eff;
  border-radius: 4px;
  font-size: 12px;
  margin-top: 8px;
}

.quantity-control {
  display: flex;
  align-items: center;
  margin: 10px 0;
  justify-content: center;
}

.quantity {
  margin: 0 10px;
  min-width: 30px;
  text-align: center;
}

.add-to-cart-btn {
  width: 100%;
  margin-top: 10px;
}

.info-item {
  margin: 10px 0;
  color: #666;
}

.info-item.time {
  color: #999;
  font-size: 12px;
  margin: 6px 0 0 0;
}

.cart-content {
  max-height: 400px;
  overflow-y: auto;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.cart-item-info {
  flex: 1;
}

.cart-item-info h4 {
  margin: 0 0 8px 0;
}

.cart-item-info p {
  margin: 5px 0;
  color: #666;
}

.cart-item-quantity {
  display: flex;
  align-items: center;
  margin: 0 15px;
}

.cart-total {
  padding: 15px;
  text-align: right;
  border-top: 1px solid #eee;
}

.total-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}
</style>

